package hu.myai.controller;

import hu.myai.model.db.AxEstimation;
import hu.myai.model.db.AxHistory;
import hu.myai.util.DatabaseUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.EntityTransaction;

import org.joone.log.ILogger;
import org.joone.log.LoggerFactory;

public class SaveEstimation {

	private static final ILogger log = LoggerFactory.getLogger(SaveEstimation.class);

	// for database util reference
	private DatabaseUtil dbUtil = new DatabaseUtil();

	public SaveEstimation() {
	}

	// save .csv files
	protected boolean saveCalculaded(String filename) {

		log.info("Get file data");

		try {
			BufferedReader inputStream = new BufferedReader(new FileReader(filename));

			// get the last result line
			String line = "";
			String lineNext;
			while ((lineNext = inputStream.readLine()) != null) {

				if (lineNext.startsWith("Best Error"))
					line = lineNext;
			}

			// prepare for process
			line = line.replaceAll("[ \t]+", " ");
			String[] items = line.split(" ");

			if (items.length > 9) {

				String symbol = items[8].substring(items[8].lastIndexOf('/') + 1, items[8].indexOf('_', items[8]
						.lastIndexOf('/')));

				String nnet = items[9].substring(items[9].lastIndexOf('/') + 1, items[9].indexOf(')', items[9]
						.lastIndexOf('/')));

				SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
				Date date = formatter.parse(items[7].substring(1, 9));

				AxEstimation estimation = new AxEstimation();

				estimation.setError(new Double(items[2].trim()));
				estimation.setEstimation1(new Double(items[4].trim()));
				estimation.setEstimation2(new Double(items[5].trim()));
				estimation.setEstimation3(new Double(items[6].trim()));
				estimation.setNnet(nnet);
				estimation.set_date(date);
				estimation.set_symbol(symbol);

				saveAxEstimation(estimation);

			}

			inputStream.close();

		} catch (IOException ex) {
			log.error("Error - File not found:" + filename);
		} catch (ParseException ex) {
		}

		return true;
	} // End method initInputStream

	protected boolean saveCalculaded(String[] filenames) {
		for (int i = 0; i < filenames.length; i++) {
			if (new File(filenames[i]).isFile()) {
				log.info("saving: " + filenames[i]);
				saveCalculaded(filenames[i]);
			}
		}
		return true;
	}

	public boolean saveAxEstimation(AxEstimation estimation) {

		Date date = estimation.get_date();
		String symbol = estimation.get_symbol();
		String nnetName = estimation.getNnet();

		EntityTransaction tx = dbUtil.entityManager.getTransaction();
		tx.begin();

		// makes child of history
		AxHistory history = dbUtil.getSavedHistory(date, symbol);
		if (history == null) {
			log.debug("Error - no history for this entry: " + symbol + " " + date);
			return false;
		}
		estimation.setAxHistory(history);

		// merge to existing record
		for (AxEstimation savedEstimation : history.getAxEstimations()) {
			if (savedEstimation.getNnet() == null || nnetName != null
					&& nnetName.equals(savedEstimation.getNnet().trim())) {
				estimation.setId(savedEstimation.getId());
				break;
			}
		}

		// save to db
		if (estimation.getId() != 0)
			dbUtil.entityManager.merge(estimation);
		else
			dbUtil.entityManager.persist(estimation);

		tx.commit();

		return true;
	}
}
